<style lang="scss" scoped>
#cmain {
    .pop {
        position: fixed;
    }
    .title {
        width: 100%;
        padding-bottom: 15px;
        border-bottom: 1px solid #DCDFE6;
        span {
            margin-left: 10px;
            font-size: 14px;
        }
        .handles {
            float: right;
            button+button {
                margin-left: 10px;
            }
        }
        button {
            padding: 2px 25px;
        }
    }
    .content {
        padding: 30px;
        min-height: 120px;
        position: relative;
        form {
            position: relative;
            &>div {
                min-height: 57px;
                display: flex;
                .ivu-form-item {
                    float: left;
                    flex: 1;
                    .ivu-date-picker {
                        width: 100%;
                    }
                }
                .ivu-form-item+.ivu-form-item {
                    margin-left: 20px;
                }
            }
            &>div.rare:nth-of-type(3) {
                .ivu-form-item:nth-of-type(1) {
                    flex: 2;
                }
            }
            &>div.rares:nth-of-type(3) {
                .ivu-form-item:nth-of-type(1) {
                    flex: 1;
                }
                
            }
            .other {
                position: absolute;
                right: 0;
                top: 173px;
                width: 100%;
            }
        }
    }
    .keepInfo {
        button {
            width: 100px;
        }
        button+button {
            margin-left: 30px;
        }
    }
    .tip-footer {
        width: 155px;
        margin: auto;
        button {
            padding: 2px 20px;
        }
    }
}
</style>
<template>
    <div id='cmain' class='cmain'>
        <Row class="main_inner">
            <Col>
            <!-- <patient-info :flag='message'></patient-info> -->
            <div class="title">
                <Icon type="person"></Icon>
                <span>病人信息（*为必填项）</span>
                <div class='handles' v-show='buttonShow'>
                    <Button type="ghost" @click="back()">返回</Button>
                    <Button type="ghost" @click="deletePatient()">删除</Button>
                    <Button type="primary" @click='change("patientInfo")'>更新</Button>
                </div>
                <div class="handles" v-show="!buttonShow">
                    <Button type="ghost" @click="back()">返回</Button>
                    <Button type="primary" @click="next('patientInfo')">下一步</Button>
                </div>
            </div>
            <div class="content">
                <Form v-if="!isShowWarn" :label-width="80" :model='patientInfo' :rules="rules" ref='patientInfo'>
                    <div>
                        <FormItem label="病人编号" prop='patientcode'>
                            <Input v-model="patientInfo.patientcode" :disabled='buttonShow'></Input>
                        </FormItem>
                        <FormItem label="病人姓名">
                            <Input v-model="patientInfo.patientname"></Input>
                        </FormItem>
                        <FormItem label="出生日期">
                            <DatePicker type="date" placeholder="选择日期" v-model="birthday" format="yyyy-MM-dd" @on-change="time"></DatePicker>
                        </FormItem>
                    </div>
                    <div>
                        <FormItem label="性别">
                            <Select v-model="patientInfo.gender">
                                <Option v-for="item in sexs" :value="item.value" :key="item.value">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                        <FormItem label="血缘关系">
                            <Input v-model="patientInfo.consanguinity"></Input>
                        </FormItem>
                        <FormItem label="民族">
                            <Input v-model="patientInfo.nation"></Input>
                        </FormItem>
                    </div>
                    <div v-if="productShow" class='rare'>
                        <FormItem label="临床描述" prop='clinicalinf'>
                            <Input type="textarea" :rows="7" placeholder="请输入不超过800个字" v-model="patientInfo.clinicalinf"></Input>
                        </FormItem>
                        <FormItem label="HPO词条" prop='chpoModelList' ref='clearchpo'>
                            <!-- <Input type="textarea" :rows="4" v-model="chpo" disabled></Input>  -->
                            <input type="hidden" v-model="patientInfo.chpoModelList" />
                            <hpolist @update='hpoupdate' :message='queryStr'></hpolist>
                        </FormItem>

                    </div>
                    <div v-else :class='rares'>
                        <FormItem label="临床描述" prop='clinicalinf'>
                            <Input type="textarea" :rows="4" placeholder="请输入不超过800个字" v-model="patientInfo.clinicalinf"></Input>
                        </FormItem>
                        <FormItem label="HPO词条" prop='chpoModelList'>
                            <hpolist @update='hpoupdate' :message='queryStr'></hpolist>
                        </FormItem>
                        <FormItem label="肿瘤类型">
                            <Select clearable v-model="patientInfo.diseasetype">
                                <Option v-for="item in diseaseTypeDefault" :value="item.value" :key="item.value">{{item.label}}</Option>
                            </Select>
                        </FormItem>
                    </div>
                    <div class="other" v-if='patientInfo.diseasetype==10'>
                        <FormItem></FormItem>
                        <FormItem></FormItem>
                        <FormItem label="其他肿瘤" prop='otherdiseasetype'>
                            <Input v-model="patientInfo.otherdiseasetype"></Input>
                        </FormItem>
                    </div>
                </Form>
                <warn @callback="getPatientInfo" v-if="isShowWarn"></warn>
            </div>
            <!-- <div class="keepInfo" v-show="!buttonShow">
                        <Button type="ghost" @click="back()">返回</Button>
                        <Button type="primary" @click="next('patientInfo')">下一步</Button>
                    </div> -->
            </Col>
            <Col v-if='buttonShow'>
            <sample :flag='message'></sample>
            </Col>
        </Row>
        <!--返回提示-->
        <Modal v-model="backModel" title="返回提示" width="300" :mask-closable="false">
            <p style="padding:20px;text-align:center;font-size:18px;">信息未保存确定返回？</p>
            <div slot='footer' class='tip-footer'>
                <Button type="ghost" @click="backCancel">取消</Button>
                <Button type="primary" @click="backClick()">确定</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
import sample from './sample'
import { data } from 'api/index.js'
import { setCookie, getCookie, delCookie } from '@/common/js/cookie.js';
import hpolist from '@/components/hpo.vue';
import warn from '@/components/warn.vue';
export default {
    name: 'editPatient',
    data() {
        const validatePatientcode = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('病人编号不能为空'));
            } else if (value.indexOf(" ") != -1) {
                callback(new Error('病人编号不能有空格'));
            } else if ((/[\u4E00-\u9FA5]/i.test(value))) {
                callback(new Error('病人编号不能含有中文'));
            } else {
                callback()
            }
        };
        const validateArray = (rule, value, callback) =>{
            if(!value || value.length<=0){
                 callback(new Error('hpo词条不能为空'));
                 $(".procee_temp_content").css("border","1px solid #ed3f14");
            }else{
                callback();
                $(".procee_temp_content").css("border","1px solid #dddee1");
            }
        };
        return {
            //限制今天之后日期不能选择
            birth: {
                disabledDate(date) {
                    return date && date.valueOf() > Date.now();
                }
            },
            queryStr: '',
            rares: 'rares',
            isShowWarn: false,
            message: {
                flags: 'edit'    //标记
            },
            oldPatientInfo: {},
            backModel: false,                 //返回提示
            buttonShow: false,                //保存按钮切换
            patientInfo: {                    //病人信息
                clinicalinf: '',
                patientcode: '',
                diseasetype: ''
            },
            chpo: '',
            birthday: '',                     //生日
            sexs: [{                          //性别
                value: 'true',
                label: "男"
            }, {
                value: 'false',
                label: "女"
            }],
            chpoModelList: [],
            rules: {
                chpoModelList: [
                    { required: true,trigger: 'change',validator: validateArray}
                ],
                clinicalinf: [
                    { required: true, message: '临床描述不能为空', trigger: 'blur' }
                ],
                patientcode: [
                    { required: true, validator: validatePatientcode, trigger: 'blur' }
                ],
                diseasetype: [
                    { required: true, message: '肿瘤类型不能为空', trigger: 'blur' }
                ],
                otherdiseasetype: [
                    { required: true, message: '其他肿瘤不能为空', trigger: 'blur' }
                ]
            },
            diseaseTypeDefault: [{
                value: '1', label: '乳腺癌'
            }, {
                value: '2', label: '子宫内膜癌'
            }, {
                value: '3', label: '结直肠癌'
            }, {
                value: '4', label: '胰腺癌'
            }, {
                value: '5', label: '胃癌'
            }, {
                value: '6', label: '前列腺癌'
            }, {
                value: '7', label: '神经系统肿瘤'
            }, {
                value: '8', label: '卵巢癌'
            }, {
                value: '9', label: '肺癌'
            }, {
                value: '10', label: '其他癌症'
            }],
            productShow: false,
            nextFlag: false,
            backFlag: false,
            update: false
        }
    },
    watch:{
        'patientInfo.chpoModelList':function(value){
            if(value && value.length>0){
                this.$refs.patientInfo.validateField("chpoModelList")
            }
        }
    },
    methods: {
        getqueryStr() {
            this.$store.state.queryStr = this.patientInfo.clinicalinf;
            this.queryStr = this.patientInfo.clinicalinf;
        },
        hpoupdate(list) {
            if (this.$store.state.chpoModelList.length == 0) {
                this.patientInfo['chpoModelList'] = this.$store.state.oldchpoModelList;
                this.patientInfo = M.clone(this.patientInfo);
            } else {
                this.patientInfo['chpoModelList'] = this.$store.state.chpoModelList;
                this.patientInfo = M.clone(this.patientInfo);
            }
            if (this.$store.state.flag == 'edit') {
                var nowchpoModelList = [];
                list.forEach(function(ele) {
                    console.log(ele)
                    let aa = ele.substring(0, ele.indexOf('('));
                    let bb = ele.substring(ele.indexOf('(') + 1, ele.lastIndexOf(')'))
                    let obj = {
                        'chpo_num': aa,
                        'chpo_en': null,
                        'chpo_cn': bb,
                    }
                    nowchpoModelList.push(obj)
                })
                if (nowchpoModelList.length == this.$store.state.oldchpoModelList.length) {
                    var aaa = nowchpoModelList.concat(this.$store.state.oldchpoModelList || [])
                    var bbb = this.heavy(aaa)
                    if (bbb.length != nowchpoModelList.length) {
                        this.update = true;
                    }

                } else {
                    this.update = true;
                }
            }
        },
        // 数组去重
        heavy(arr) {
            var res = [];
            var json = {};
            for (var i = 0; i < arr.length; i++) {
                if (!json[JSON.stringify(arr[i])]) {
                    res.push(arr[i]);
                    json[JSON.stringify(arr[i])] = 1;
                }
            }
            return res;
        },
        time(e) {
            this.birthday = e;
        },
        //判断两个对象是否相等
        diff(obj1, obj2) {
            var o1 = obj1 instanceof Object;
            var o2 = obj2 instanceof Object;
            if (!o1 || !o2) {/*  判断不是对象  */
                return obj1 === obj2;
            }
            // if (Object.keys(obj1).length !== Object.keys(obj2).length) {
            //     return false;
            // }
            for (var attr in obj1) {
                var t1 = obj1[attr] instanceof Object;
                var t2 = obj2[attr] instanceof Object;
                if (t1 && t2) {
                    return diff(obj1[attr], obj2[attr]);
                } else if (obj1[attr] !== obj2[attr]) {
                    return false;
                }
            }
            return true;
        },
        //创建病人信息相关数据
        setPatientInfo(obj) {
            return {
                patientid: obj.patientid,
                patientcode: obj.patientcode,
                patientname: obj.patientname,
                birthday: obj.birthday,
                gender: obj.gender,
                consanguinity: obj.consanguinity,
                nation: obj.nation,
                clinicalinf: obj.clinicalinf,
                diseasetype: obj.diseasetype
                //    description: "",
                //    chpo:""
            }
        },
        //获取病人信息相关数据
        getPatientInfos() {
            return {
                patientid: this.patientInfo.patientid,
                patientcode: this.patientInfo.patientcode,
                patientname: this.patientInfo.patientname,
                birthday: this.formatDate(this.birthday),
                gender: this.getGender(this.patientInfo.gender),
                consanguinity: this.patientInfo.consanguinity,
                nation: this.patientInfo.nation,
                clinicalinf: this.patientInfo.clinicalinf,
                diseasetype: this.patientInfo.diseasetype
            }
        },
        //转换性别类型
        getGender(str) {
            if (str == "false") {
                return 'false';
            } else if (str == "true") {
                return 'true';
            } else {
                return 'null';
            }
        },
        formatDate(date) {
            var youWant;
            if (date != '') {
                var d = new Date(date);
                var month, dates;
                if (d.getMonth() + 1 < 10) {
                    month = '-0' + (d.getMonth() + 1)
                } else {
                    month = '-' + d.getMonth() + 1
                }
                if (d.getDate() < 10) {
                    dates = '-0' + d.getDate()
                } else {
                    dates = '-' + d.getDate()
                }
                youWant = d.getFullYear() + month + dates;
            } else {
                youWant = ''
            }
            return youWant;
        },
        //验证病人信息是否修改
        validatePatientInfo() {
            var ret = true
            var nowPatientInfo = this.getPatientInfos();   //现在的病人信息
            if (this.$store.state.flag == 'add') {
                var n = 0
                for (let key in nowPatientInfo) {
                    if (nowPatientInfo[key] != '' && nowPatientInfo[key] != undefined && nowPatientInfo[key] != 'null') {
                        n += 1
                    }
                }
                if (n > 0) {
                    return false;
                }
            } else if (this.$store.state.flag == 'edit') {
                if (!this.diff(nowPatientInfo, this.oldPatientInfo)) {
                    return false;
                }
            }
            return ret;
        },
        //删除病人
        deletePatient() {
            this.$confirm('该条数据将被删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let obj = { idList: [this.$store.state.patientid] }
                data.deletePatientById(obj).then((res) => {
                    if (res.returnCode == 0 || res.returnCode == 200) {
                        this.$Message.success(res.msg)
                        if (this.$store.state.productId == 1) {
                            this.$router.push("/rare");
                        } else if (this.$store.state.productId == 2) {
                            this.$router.push("/tumor");
                        }
                    } else {
                        this.$Message.error(res.msg)
                    }
                })
            })
            
        },
        //返回
        back() {
            this.$store.state.pageindex = 1;
            if (this.$store.state.productId == 1) {
                this.$router.push("/rare");
            } else if (this.$store.state.productId == 2) {
                this.$router.push("/tumor");
            }

        },
        //返回确定
        backClick() {
            this.backFlag = true;
            this.patientInfo = {
                clinicalinf: '',
                patientcode: ''
            }
            if (this.$store.state.productId == 1) {
                this.$router.push("/rare");
            } else if (this.$store.state.productId == 2) {
                this.$router.push("/tumor");
            }
        },
        //返回取消
        backCancel() {
            this.backModel = false;
        },
        //下一步
        next(info) {
            this.nextFlag = true;
            let obj = {
                userId: getCookie("userid"),
                productId: this.$store.state.productId,
                projecttype: '1'
            }
            this.patientInfo['chpoModelList'] = this.$store.state.chpoModelList;
            this.patientInfo['birthday'] = this.formatDate(this.birthday);
            obj["patient"] = this.patientInfo;
            if (this.patientInfo.diseasetype != '10') {
                this.patientInfo.otherdiseasetype = ''
            }
            this.$refs[info].validate((valid) => {
                if (valid) {
                    data.addProject(obj).then((res) => {
                        if (res.returnCode == 0 || res.returnCode == 200) {
                            this.$store.state.patientid = res.data.patient.patientid;
                            this.$router.push('/rare/addSample')
                        } else if (res.returnCode == 102) {
                            this.$Message.error(res.msg)
                        } else {
                            this.$Message.error(res.msg)
                        }
                    })
                }
            })

        },
        //更新
        change(info) {
            console.log(info)
            this.nextFlag = true;
            this.patientInfo['chpoModelList'] = this.$store.state.chpoModelList;
            this.patientInfo['birthday'] = this.formatDate(this.birthday);
            this.patientInfo['chpoState'] = this.update;
            if (this.patientInfo.diseasetype != '10') {
                this.patientInfo.otherdiseasetype = ''
            }
            this.$refs[info].validate((valid) => {
                if (valid) {
                    data.updatePatient(this.patientInfo).then((res) => {
                        if (res.returnCode == 0 || res.returnCode == 200) {
                            if (this.$store.state.productId == 1) {
                                this.$router.push("/rare");
                            } else if (this.$store.state.productId == 2) {
                                this.$router.push("/tumor");
                            }
                        } else {
                            this.$Message.error(res.msg)
                        }
                    })
                }
            })
        },
        //获取病人信息
        getPatientInfo() {
            let that = this;
            let obj = {
                "patientid": this.$store.state.patientid,
                "userId": getCookie("userid"),
                "productId": this.$store.state.productId
            }
            data.getProjectDetail(obj).then((res) => {
                console.log(res)
                if (res.returnCode == 0 || res.returnCode == 200) {
                    console.log(this.patientInfo.gender)
                    this.patientInfo = res.data.dchPatient;
                    this.patientInfo.gender = String(this.patientInfo.gender)
                    this.birthday = this.patientInfo.birthday;
                    this.$store.state.birthday = this.birthday;
                    if (this.patientInfo.chpoModelList != null) {
                        this.patientInfo.chpoModelList.forEach(function(ele) {
                            that.chpo += ele.chpo_num + '(' + ele.chpo_cn + ')' + '\n'
                        })
                    }
                    this.oldPatientInfo = $.extend({}, this.patientInfo)
                    // if (this.patientInfo.clinicalinf != '') {
                    //     this.getchpo()
                    // }
                }
                this.isShowWarn = false;
            }).catch((error) => {
                this.isShowWarn = true;
            })
        }
    },
    mounted() {
        switch (this.$store.state.flag) {
            case 'add':
                this.buttonShow = false;
                this.$store.state.patientid = '';
                break;
            case 'edit':
                this.getPatientInfo();
                this.buttonShow = true;
                this.rares = '';
                break;
        }
        this.productShow = this.$store.state.productId == '1' ? true : false;
    },
    components: {
        sample,
        hpolist,
        warn
    },
    beforeRouteLeave(to, from, next) {
        if (to.path == '/rare' || to.path == '/tumor') {
            if (this.nextFlag == false && this.backFlag == false) {
                if (this.validatePatientInfo() && this.update == false) {
                    next()
                } else {
                    this.backModel = true;
                }
            } else {
                next()
            }
        } else {
            next()
        }
    }
}
</script>>

